import os

import sys
from typing import Dict, Any

import logging

from logging.config import fileConfig

import datetime

import json

import schedule
from pymongo.cursor import Cursor

from schedule import every, repeat, run_pending

import time

from functools import wraps

import configparser

from datetime import datetime,timedelta

import hashlib

from mongo.MongoHelper import MongoHelper

from findata.akshare.AkshareWeekly import AkshareWeekly
from findata.akshare.AkshareDaily import AkshareDaily
from findata.akshare.AkshareQuarterly import AkshareQuarterly
from findata.akshare.AkshareMonthly import AkshareMonthly
from findata.akshare.AkshareBiWeekly import AkshareBiWeekly
from findata.akshare.AkshareYearly import AkshareYearly
from findata.mairui.freeData import equity_list

fileConfig('logging_config.ini', disable_existing_loggers=False)
logger = logging.getLogger('simple_example')
mongoHelper = None

def theJob():
    print('The job is running')
    logger.info("================================")
cfgdir = os.path.split(os.path.realpath(__file__))[0]
print(cfgdir)
cfg = os.path.join(cfgdir, 'config.cfg')

#
config = configparser.ConfigParser()
if len(sys.argv) >= 2:
    config.read(sys.argv[1])
else:
    config.read('./config.cfg')
database = config.get('db', 'database')
myUrl = config.get('db', 'url')
mongoHelper = MongoHelper(url=myUrl, database=database)

akshareWeekly = AkshareWeekly(cfg=cfg)

@staticmethod
def last_day_of_quarter(year, quarter):
    # 每个季度的最后一个月，第三个参数是月份的最后一天
    months = ((1, 3, 31), (4, 6, 30), (7, 9, 30), (10, 12, 31))
    # 季度是从1开始的，所以减1来获取正确的月份
    month = months[quarter - 1]
    # 使用年份和季度的最后一个月来创建datetime对象
    return datetime(year, month[1], month[2])
@staticmethod
def get_his():
    list = akshareWeekly.get_all_equities()
    for rec in list:
        akshareWeekly.ahist(symbol=rec['code'], period='daily', start_date='20240101', end_date='20240620', adjust='hfq')

@staticmethod
def get_equity_list():
    equity_list()

@staticmethod
def get_lending_list():
    akshareWeekly.lending_securities(code=akshareWeekly.get_all_equities())

@staticmethod
def get_repurchase_list():
    akshareWeekly.equityrepurchase()

@staticmethod
def get_free_holder_list():
    list = akshareWeekly.get_all_equities()
    for record in list:
        for item in range(2014,2024):
            for ele in range(1,4):
                akshareWeekly.freeHolder(symbol=record['code'],begdate=last_day_of_quarter(item,ele).strftime('%Y%m%d'))
@staticmethod
def get_retail_investor_list():
    for record in akshareWeekly.get_all_equities():
        akshareWeekly.numofretailinvestor(symbol=record['code'])

@staticmethod
def get_market_fund_flow():
    akshareWeekly.maketfundflow()

@staticmethod
def get_big_deal():
    akshareWeekly.bigdealtrack()

@staticmethod
def get_holder_decrease():
    for record in akshareWeekly.get_all_equities():
        akshareWeekly.holder(symbol=record['code'])

@staticmethod
def get_pledgeRatio():
    # 定义开始日期
    start_date = datetime(2024, 6, 1)
    # 定义结束日期
    end_date = datetime(2024, 6, 30)
    # 生成日期范围
    date_range = [start_date + timedelta(days=i) for i in range((end_date - start_date).days + 1)]
    # 打印日期范围
    for p_date in date_range:
        akshareWeekly.pledgeRatio(begdate=p_date.strftime("%Y-%m-%d"))


@staticmethod
def get_block_transaction_details():
    for record in akshareWeekly.get_all_equities():
        akshareWeekly.blockTransactionDetails(symbol=record['code'],begDate='20240501',endDate='20240630')


@staticmethod
def get_core_biz():
    for record in akshareWeekly.get_all_equities():
        akshareWeekly.coreBiz(symbol=record['code'])

@staticmethod
def get_financing_securities():
    # 定义开始日期
    start_date = datetime(2024, 6, 1)
    # 定义结束日期
    end_date = datetime(2024, 6, 30)
    # 生成日期范围
    date_range = [start_date + timedelta(days=i) for i in range((end_date - start_date).days + 1)]
    # 打印日期范围
    for p_date in date_range:
        akshareWeekly.financingSecurities(data=p_date.strftime("%Y%m%d"))

@staticmethod
def get_instituteHolding():
    for record in akshareWeekly.get_all_equities():
        akshareWeekly.instituteHolding(symbol=record["code"])

@staticmethod
def get_individual_cash_flow():
    for record in akshareWeekly.get_all_equities():
        akshareWeekly.individualCashFlow(code=record['code'],market=record['exchange'])

if __name__ == '__main__':



    # akshareWeekly.ahist(symbol='600487', period='', start_date='', end_date='', adjust='')
    # akshareWeekly.industryFlow()
    # akshareWeekly.blockTransactionDetails(symbol='A股',  startDate='20240101', endDate='20240131')
    # akshareWeekly.holder(symbol='全部')
    # akshareWeekly.bigdealtrack()
    # akshareWeekly.numofretailinvestor(symbol='20231231')
    # akshareWeekly.fundHolder(symbol='基金持仓',begdate='20240501')
    # akshareWeekly.assetbalance(begdate='20231231')
    # akshareWeekly.cashflow(begdate='20231231')
    # akshareWeekly.financialindicator(symbol='600487',begdate='2023')

    # akshareWeekly.hkfinancialindicator(symbol='600487',begdate='2023')

    # akshareWeekly.freeHolder(symbol='sh600487',begdate='20231231')

    # akshareWeekly.conceptcashflow(symbol='即时')

    # 使用lambda函数来包装你的任务和它的参数
    # schedule.every(10).seconds.do(lambda: job("Alice", 30))
    # schedule.every(10).seconds.do(my_job,name='Alice',age=30)
    # schedule.every().monday.do(theJob)
    # schedule.every(10).seconds.do(theJob)
    # 每十分钟执行任务
    # schedule.every(2).minutes.do(theJob)
    # 每个小时执行任务
    # schedule.every().hour.do(theJob)
    # 每天的10:30执行任务
    # schedule.every().day.at("00:50:00").do(lambda: akshareWeekly.basicInfo(symbol='600487'))
    schedule.every().day.at("00:00:00").do(lambda: get_equity_list())
    schedule.every().day.at("00:30:00").do(lambda: get_his())
    schedule.every().day.at("03:00:00").do(lambda:get_lending_list())
    # 每个月执行任务
    # schedule.every().monday.do(theJob)
    # 每个星期三的13:15分执行任务
    # schedule.every().wednesday.at("13:15").do(theJob)
    # 每分钟的第17秒执行任务
    # schedule.every().minute.at(":17").do(theJob)
    # do() 将额外的参数传递给job函数
    # schedule.every(2).seconds.do(greet, name='Alice')
    # all_jobs = schedule.get_jobs()

    # .tag 打标签
    # schedule.every().day.do(greet, 'Andrea').tag('daily-tasks', 'friend')

    # 每个小时运行作业，2030-01-01 18:33 today
    # schedule.every(1).hours.until("2030-01-01 18:33").do(job)

    # 每个小时运行作业，8个小时后停止
    # schedule.every(1).hours.until(timedelta(hours=8)).do(job)


    # schedule.clear()
    while True:
        schedule.run_pending()
        time.sleep(1)
